import { useRouter } from 'vue-router'
import { login } from '@/service/modules/login'
import { getUserInfoReq } from '@/service/modules/user'
import { useUserStore } from '@/store/user/user'
import type { Router } from 'vue-router'
import type { Token } from '@/service/modules/login/types'
import type { Response } from '@/service/modules/common/types'
import { UserInfo } from '@/service/modules/user/types'
// import { useTimezoneStore } from '@/store/timezone/timezone'

export function useLogin(state: any) {
  const router: Router = useRouter()
  const userStore = useUserStore()
  // const timezoneStore = useTimezoneStore()

  const handleLogin = () => {
    state.loginFormRef.validate(async (valid: any) => {
      if (!valid) {
        //登录
        const loginRes: Response<Token> = await login({ ...state.loginForm })
        userStore.setToken(loginRes.data.access_token)
        //获取用户信息
        const userInfoRes: Response<UserInfo> = await getUserInfoReq()
        userStore.setUserInfo(userInfoRes.data)

        // const timezone = userInfoRes.timeZone ? userInfoRes.timeZone : 'UTC'
        // await timezoneStore.setTimezone(timezone)
        router.push({
          path: '/home',
          query: {
            tab: window.$t('common.home'),
            tabName: 'HomeTab'
          }
        })
      }
    })
  }

  return {
    handleLogin
  }
}
